#include "lisctl.h"
#include "myposix.h"
#include "wiringPi.h"

#define FIRE_PIN 6

int fir_init(void)
{
    printf("%s|%s|%d\n", __FILE__, __func__, __LINE__);
    pinMode(FIRE_PIN, INPUT);
    return 0;
}

void *fir_get(void *arg)
{
    mqd_t mqd = -1;
    posix_pt p = (posix_pt)arg;
    if (NULL != p)
    {
        mqd = p->mqd;
    }
    if (-1 == mqd)
    {
        printf("%s|%s|%d:mqd = %d\n", __FILE__, __func__, __LINE__, mqd);
        pthread_exit(0);
    }

    int flag = 0;
    int tmp = HIGH;
    unsigned char buf[6] = {0xAA, 0x55, 0x00, 0x00, 0x55, 0xAA};

    pthread_detach(pthread_self());
    printf("%s thread start\n", __func__); 
    while (1)
    {
        tmp = digitalRead(FIRE_PIN);
        if (LOW == tmp)
        {
            flag = 1;
            buf[2] = 0x32;
            buf[3] = 0x00;
            posix_send(mqd, buf, 6);
            printf("%s|%s|%d:gets->0x%X,0x%X,0x%X,0x%X,0x%X,0x%X\n", __FILE__, __func__, __LINE__,
                   buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
        }

        else if (1 == flag && HIGH == tmp)
        {
            flag = 0;
            buf[2] = 0x32;
            buf[3] = 0x01;
            posix_send(mqd, buf, 6);
            printf("%s|%s|%d:gets->0x%X,0x%X,0x%X,0x%X,0x%X,0x%X\n", __FILE__, __func__, __LINE__,
                   buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
        }
        sleep(5);
    }
    pthread_exit(0);
}

listen_node fire_stu = {
    .listen_name = "fire",
    .init = fir_init,
    .final = NULL,
    .get = fir_get,
    .set = NULL,
    .next = NULL};

listen_pt fir_add(listen_pt lisHead)
{
    return lis_add(lisHead, &fire_stu);
}